package com.ym.wcp.framework.config;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ym.wcp.framework.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@Configuration
@EnableRedisHttpSession
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${redis.cache.expiration:30}")
    private Integer expiration;

    @Autowired
    private JedisConnectionFactory redisConnectionFactory;

    /**
     * springboot 1.x
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(expiration);
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }

    @Bean
    public RedisUtil getRedisUtil() {
        return new RedisUtil();
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate();
        templateConfiguration(template);
        return template;
    }


    @Bean
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<?, ?> template = new RedisTemplate<>();
        templateConfiguration(template);
        return template;
    }

    private void templateConfiguration(RedisTemplate<?, ?> template) {
        // 配置连接工厂
        template.setConnectionFactory(setRedisConnectionFactoryPoll(redisConnectionFactory));
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
    }

    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            sb.append("&");
            sb.append(JSONUtil.toJsonStr(params));
            return DigestUtil.sha1Hex(sb.toString());
        };
    }


    private JedisConnectionFactory setRedisConnectionFactoryPoll(JedisConnectionFactory connectionFactory) {
        //配置连接池属性
        connectionFactory.setTimeout(15000);
        //控制一个pool可分配多少个jedis实例
        connectionFactory.getPoolConfig().setMaxIdle(10);
        //最大空闲数
        connectionFactory.getPoolConfig().setMaxTotal(100);
        //最大等待时间
        connectionFactory.getPoolConfig().setMaxWaitMillis(15000);
        //连接的最小空闲时间 默认1800000毫秒(30分钟)
        connectionFactory.getPoolConfig().setMinEvictableIdleTimeMillis(30000);
        //每次释放连接的最大数目,默认3
        connectionFactory.getPoolConfig().setNumTestsPerEvictionRun(1024);
        //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        connectionFactory.getPoolConfig().setTimeBetweenEvictionRunsMillis(30000);
        //是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
        connectionFactory.getPoolConfig().setTestOnBorrow(true);
        //在空闲时检查有效性, 默认false
        connectionFactory.getPoolConfig().setTestWhileIdle(true);
        return connectionFactory;
    }
}
